<template>
  <page-wrap stay-still back hide-tab title="个人证书">
    <view class="form-wrap" :style="'margin-bottom:' + inputBottom + 'px;'">
      <u-form :model="form" ref="uForm" label-position="top" class="form">
        <block v-for="(item, index) in formList" :key="index">
          <view
            class="form-item-wrap"
            @click.capture="handleSelect(item, index)"
          >
            <u-form-item
              :class="[{ pick: item.comp }, { multiple: item.multiple }]"
              :label="item.label"
              :prop="item.prop"
              :border-bottom="!item.hideBorderBottom"
            >
              <!-- textarea -->
              <my-textarea
                v-if="!item.comp && item.type === 'textarea'"
                class="form-text"
                :value="form[item.prop]"
                :placeholder="item.inputPlaceholder"
                :maxlength="item.maxlength"
                auto-height
                show-word-limit
                @update:value="handleClear($event, item)"
                @board-change="handleBottom"
              ></my-textarea>
              <template v-else>
                <u-input
                  v-if="item.comp != 'upload'"
                  :class="[
                    'form-input',
                    { textarea: item.inputType === 'textarea' },
                  ]"
                  v-model="form[item.prop]"
                  :disabled="!!item.comp"
                  :placeholder="item.inputPlaceholder"
                  :type="item.inputType"
                  :height="item.height"
                  :maxlength="item.maxlength || 150"
                  :clearable="false"
                />
              </template>
 
              
              <text v-if="item.multiple">~</text>
              <u-input
                v-if="item.multiple"
                class="form-input"
                v-model="form[item.prop2]"
                :disabled="!!item.comp"
                :placeholder="item.inputPlaceholder2"
                :clearable="false"
                @click="handleMultipleSelect(item)"
              />

              <!-- 下拉选择 -->
              <u-select
                class="form-select"
                v-model="item.show"
                :list="item.data"
                v-if="item.comp === 'select'"
                @confirm="handleConfirm($event, item)"
              ></u-select>
              <!-- 时间选择 -->
              <u-picker
                class="form-time"
                mode="time"
                v-model="item.show"
                :params="item.param"
                :start-year="item.start"
                :end-year="item.end"
                :default-time="form[item.propDefault]"
                v-if="item.comp === 'time'"
                @confirm="handleConfirm($event, item)"
              ></u-picker>
              <view v-if="item.comp === 'upload'">
                <u-upload :action="action" :upload-text="item.inputPlaceholder" :file-list="fileList" max-count="1" @on-success="handleUploadSuccess($event, item)"
                @on-remove="handleRemove(item)"></u-upload>
              </view>
            </u-form-item>
          </view>
        </block>
      </u-form>
    </view>

    <view class="page-action">
      <view class="btn-delete" v-if="form.id">
        <u-button
          :hair-line="false"
          :plain="true"
          :custom-style="btnSaveStyle"
          @click="handleDelete"
          >删除</u-button
        >
      </view>
      <view class="btn-save">
        <u-button type="primary" :custom-style="btnStyle" @click="handleSave"
          >保存</u-button
        >
      </view>
    </view>
  </page-wrap>
</template>

<script>
import {
  addCer,
  updateCer,
  deleteCer,
  getResumeData,
  uploadAction,
  getFileByUrl,
} from "@/api/index";
// import { certificateList } from "@/utils/certificate";
import MyTextarea from "../components/MyTextarea.vue";
import ShareMixin from '@/mixins/share';
import { throttle } from "lodash";

export default {
  mixins: [ShareMixin],
  components: {
    MyTextarea,
  },
  data() {
    return {
      inputBottom: 0,
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      cerId: "",
      info: {},
      form: {},
      certificateList: [],
      formList: [
        {
          label: "获得时间",
          multiple: false,
          prop: "time",
          propDefault: 'timeDefault',
          inputPlaceholder: "请选择",
          comp: "time",
          show: false,
          param: {
            year: true,
            month: true,
            day: false,
            hour: false,
            minute: false,
            second: false,
          },
          setYearsMonths: true,
          start: new Date().getFullYear() - 70,
          end: new Date().getFullYear(),
        },
        {
          label: "证书类型",
          prop: "CerList",
          inputPlaceholder: "请选择",
          comp: "select",
          show: false,
          data: [],
        },
        {
          label: "证书名称",
          prop: "CertName",
          inputPlaceholder: "请选择",
          comp: "select",
          show: false,
          data: [],
        },
        {
          label: "证书成绩",
          prop: "Scores",
          inputPlaceholder: "选填",
          type: 'input'
        },
        {
          label: "上传证书图片",
          prop: "filepath",
          inputPlaceholder: "上传证书图片",
          comp: 'upload',
        },
      ],
      modelVisible: false,
      btnSaveStyle: {
        border: "none",
        backgroundColor: "#E9ECEF",
      },
      btnStyle: {
        border: "none",
      },
      rules: {
        time: [
          {
            required: true,
            message: "请选择",
          },
        ],
        CerList: [
          {
            required: true,
            message: "请选择",
          },
        ],
        CertName: [
          {
            required: true,
            message: "请选择",
          },
        ],
      },
      cerNameList: [],
      action: uploadAction,
      fileList: [],
      isIOS: uni.getSystemInfoSync().platform == 'ios'
    };
  },
  watch: {
    info: {
      handler(val) {
        if (val.personCerArr) {
          let cerItem = val.personCerArr.find((ele) => ele.id === this.cerId);
          this.form = JSON.parse(JSON.stringify(cerItem));
          this.$set(this.form, "time", `${cerItem.Years}-${cerItem.Months}`);
          this.$set(this.form, "timeDefault", `${cerItem.Years}-${cerItem.Months}`);
          if(this.isIOS) {
            this.$set(this.form, "timeDefault", `${cerItem.Years}/${cerItem.Months}/01`);
          }

          if(cerItem.filepath) this.fileList = [{url: cerItem.filepath}];
        }
      },
      deep: true,
      immediate: true,
    },
    inputBottom(val) {
      if (val) {
        this.$nextTick(() => {
          uni.pageScrollTo({
            scrollTop: 99999,
            duration: 0,
          });
        });
      }
    },
    "form.CerList"(val, oldVal) {
      let cerListItem = this.certificateList.find((item) => {
        return item.label == val;
      });
      cerListItem = JSON.parse(JSON.stringify(cerListItem));
      if (cerListItem) {
        if (cerListItem.label == "自定义") {
          this.formList[2].comp = "";
          this.formList[2].type = "input";
        } else if (!this.formList[2].comp) {
          this.formList[2].comp = "select";
          this.formList[2].type = "";
        }
        let cerNameList = cerListItem.children || [];
        this.formList[2].data = cerNameList;
        val && oldVal && (this.form.CertName = "");
      }
      return [];
    },
  },
  onLoad(options) {
    if (options.id) {
      this.cerId = options.id;
      this.getResumeData();
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },

  created() {
    getFileByUrl('https://img3.job1001.com/ypMp/elan/files/certificate.json').then(res => {
      this.certificateList = res;
      this.formList[1].data = res;
    })
  },
  methods: {
    handleBottom(e) {
      this.inputBottom = e > 130 ? e - 130 : 0;
    },
    handleClear(e, item) {
      this.$set(this.form, item.prop, e);
    },
    getResumeData() {
      if (
        !getApp().globalData.resumeInfo ||
        !getApp().globalData.resumeInfo.id
      ) {
        let param = {
          personId: this.personId,
          conditionArr: JSON.stringify({
            is_mp: 1,
          }),
        };
        getResumeData(param).then((res) => {
          this.info = res;
        });
      } else {
        this.info = JSON.parse(JSON.stringify(getApp().globalData.resumeInfo));
      }
    },
    handleUploadSuccess(data, item) {
      let filePath = 'http://img106.job1001.com/' + data
      this.$set(this.form, item.prop, filePath)
    },
    handleSave: throttle(function () {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.saveCer();
        }
      });
    },3000),
    // 添加/修改
    saveCer() {
      let list = this.form;

      let params = {};
      let dataArr = {
        Years: list.Years,
        Months: list.Months,
        CerList: list.CerList,
        CertName: list.CertName,
        Scores: list.Scores,
        filepath: list.filepath,
        uid: this.personId,
      };
      
      let fcn = addCer;
      let successTxt = "添加成功";
      if (list.id) {
        fcn = updateCer;
        successTxt = "修改成功";
        dataArr.id = list.id;
        params.person_id = this.personId;
        params.updateArr = JSON.stringify(dataArr);
      } else {
        params.cerArr = JSON.stringify(dataArr);
      }
      fcn(params)
        .then((res) => {
          if (res.code == 200) {
            uni.showToast({
              icon: "none",
              title: successTxt,
              complete() {
                setTimeout(() => {
                  uni.navigateBack();
                }, 1500);
              },
            });
          } else {
            uni.showToast({ icon: "none", title: res.status_desc });
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleDelete() {
      uni.showModal({
        title: "温馨提示",
        content: `确认删除个人证书？`,
        success: (modalRes) => {
          if (modalRes.confirm) {
            let params = {
                person_id: this.personId,
                cer_id: this.form.id,
            };
            deleteCer(params)
              .then((res) => {
                if (res.code == 200) {
                  uni.showToast({
                    icon: "none",
                    title: "删除成功",
                    complete() {
                      setTimeout(() => {
                        uni.navigateBack();
                      }, 1500);
                    },
                  });
                } else {
                  uni.showToast({ icon: "none", title: res.status_desc });
                }
              })
              .catch((err) => {
                console.error(err);
              });
          }
        },
      });
    },
    handleSelect(item, index) {
      if (item.comp) {
        this.$set(item, "show", true);
      }
    },
    handleMultipleSelect(item) {
      if (item.multiple) {
        this.$set(item, "setProp2", true);
      }
    },
    handleConfirm(e, item) {
      if (Array.isArray(e)) {
        this.$set(this.form, item.prop, e[0].label);
        if (item.propVal) {
          this.$set(this.form, item.propVal, e[0].value);
        }
      } else {
        let time = `${e.year}-${e.month}`;
        if (item.param && item.param.day) {
          time = `${e.year}-${e.month}-${e.day}`;
        }

        if (item.setProp2) {
          this.$set(this.form, item.prop2, time);
          this.$set(item, "setProp2", false);
          return;
        }
        if (item.setYearsMonths) {
          this.$set(this.form, "Years", e.year);
          this.$set(this.form, "Months", e.month);
        }
        this.$set(this.form, item.prop, time);
      }
    },
    handleRemove(item) {
      this.$set(this.form, item.prop, '')
    }
  },
};
</script>

<style lang="scss">
$img-base-resume: $img-base + "resume/";
.form-wrap {
  flex-grow: 1;
  ::v-deep .u-form {
    padding-top: 0;
    margin: 32rpx 32rpx 0;
    padding: 32rpx 32rpx 0;
    background-color: $uni-bg-color;
    border-radius: $uni-border-radius-big;
    .form-text {
      display: block;
      width: calc(100vw - 128rpx);
      box-sizing: border-box;
      .textarea-input {
        background-color: #f8f9fb;
        border-radius: $uni-border-radius-big;
        textarea,
        .textarea {
          height: 260rpx !important;
          font-size: $uni-font-size-sm;
        }
        .placeholder {
          font-size: $uni-font-size-sm;
        }
      }
    }
    .textarea {
      background-color: #f8f9fb;
      border-radius: $uni-border-radius-big;
      .u-input {
        background-color: #f8f9fb;
        border-radius: $uni-border-radius-big;
      }
    }
    .u-input__textarea {
      padding: 24rpx 32rpx;
      font-size: $uni-font-size-nor;
    }
    .content-words {
      margin-right: 10rpx;
      text-align: right;
      color: $uni-text-color-888;
      font-size: $uni-font-size-sm;
    }
  }
}
</style>